# 数据库连接

# pymysql用connect方法进行连接
import pymysql
from flask import Flask, render_template, request, redirect, url_for, session

app = Flask(
    __name__
)
app.secret_key = '123456'  # 加密会话数据

conn = pymysql.connect(host="localhost", port=3306,
                       user="root", password="123456",
                       database="demo01", charset="utf8mb4")


def con_my_sql(sql_code):
    try:
        conn.ping(reconnect=True)  # 保证数据库连接正常
        print(sql_code)
        # 通过游标对象对数据库服务器发出sql语句
        cursor = conn.cursor(pymysql.cursors.DictCursor)  # 返回数据是字典形式，而不是数组
        cursor.execute(sql_code)
        # 提交
        conn.commit()
        # 关闭连接
        conn.close()
        return cursor  # 普通执行返回1 就是执行成功

    except pymysql.MySQLError as err_massage:
        # 回滚
        conn.rollback()
        # 关闭连接
        conn.close()
        return type(err_massage), err_massage


#
# username = "张三"
# pwd = '123456'
# code = "INSERT INTO `login_user` (`username`, `password`) VALUES ('%s','%s')" % (username, pwd)
# print(con_my_sql(code))

# username = "张三"
# pwd = '123456'
# code = "select * from login_user where username='%s'" % (username)
# cursor_ans = con_my_sql(code)
# print(cursor_ans.fetchall()) # 查询测试

# @app.route("/index")
# def index():
#     return render_template("index.html")


@app.route("/index")
def index():
    if 'username' in session:  # Check if the user is logged in
        return render_template("index.html")
    else:
        return redirect(url_for("index_login"))  # Redirect to login if not logged in


@app.route("/profile")
def profile():
    if 'username' in session:  # Check if the user is logged in
        return render_template("profile.html")
    else:
        return redirect(url_for("index_login"))  # Redirect to login if not logged in


@app.route("/")
def index_login():
    return render_template("login.html")


@app.route("/index_register")
def index_register():
    return render_template("register.html")


@app.route("/login", methods=['POST'])
def login():
    name = request.form.get("username")
    pwd = request.form.get("password")
    code = "select * from login_user where username='%s'" % (name)
    cursor_ans = con_my_sql(code)
    data_select = cursor_ans.fetchall()
    if len(data_select) > 0:
        data_select = data_select[0]
        if pwd == data_select['password']:
            session['username'] = name  # Set session for logged-in user
            return redirect(url_for("index"))  # 返回后台主页
        else:
            # 如果密码错误，弹出提示框
            return '''
            <script>
                alert('密码错误');
            </script>
            '''
    else:
        # 如果用户不存在，弹出提示框
        return '''
        <script>
            alert('用户不存在');
        </script>
        '''


@app.route("/logout")
def logout():
    session.pop('username', None)  # Clear the session
    return redirect(url_for("index_login"))


@app.route("/register", methods=['POST'])
def register():
    name = request.form.get("username")
    pwd = request.form.get("password")
    pwd2 = request.form.get("password2")
    if pwd != pwd2:
        # 密码检查
        return '''
        <script>
            alert('两次输入密码不相等');
            window.location.href = "index_register";
        </script>
        '''
    code = "select * from login_user where username='%s'" % (name)
    cursor_ans = con_my_sql(code)
    data_select = cursor_ans.fetchall()
    if len(data_select) > 0:
        # 如果用户存在，弹出提示框
        return '''
        <script>
            alert('用户已存在');
            window.location.href = "index_register";
        </script>
        '''
    else:
        code = "INSERT INTO `login_user` (`username`, `password`) VALUES ('%s','%s')" % (name, pwd)
        con_my_sql(code)
        # 注册成功
        return '''
        <script>
            alert('注册成功');
            window.location.href = "/";
        </script>
        '''


if __name__ == '__main__':
    app.run(port=5002,debug=True)
